import React from 'react'
import { Upload, Icon, Modal, notification } from 'antd'
import * as qiniu from 'qiniu-js'
import PropTypes from 'prop-types'

import API from '@common/api.js'

class PicturesWall extends React.Component {
  state = {
    qiniuToken: '',
    baseUrl: '',
    previewvisible: false,
    previewImage: '',
    fileList: [],
    imageUrlList: []
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true
    })
  }

  handleChange = ({ fileList }) => {
    this.setState({ fileList })
  }

  handlePostSuccess = imgUrl => {
    this.setState(value => ({
      imageUrlList: [...value.imageUrlList, imgUrl]
    }))
    this.props.successCb(this.state.imageUrlList)
  }

  handleRemove = async file => {
    let imgUrl = this.state.baseUrl + '/' + file.response.key
    let index = this.state.imageUrlList.indexOf(imgUrl)
    if (index >= 0) {
      await this.setState(value => {
        value.imageUrlList.splice(index, 1)
        return {
          imageUrlList: [...value.imageUrlList]
        }
      })
    }

    this.props.successCb(this.state.imageUrlList)
  }

  render() {
    const { previewVisible, previewImage, fileList } = this.state
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    )
    return (
      <div className="clearfix">
        <Upload
          accept=".jpeg, .jpg, .png, .gif"
          multiple={true}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          onRemove={this.handleRemove}
          customRequest={this.handleRequest}
        >
          {fileList.length >= 9 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="上传九宫格" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  }

  handleRequest = ({
    data,
    file,
    filename,
    onError,
    onProgress,
    onSuccess,
    withCredentials
  }) => {
    try {
      const formData = new FormData()
      if (data) {
        Object.keys(data).map(key => {
          formData.append(key, data[key])
        })
      }
      formData.append(filename, file)

      const { baseUrl, token } = this.state

      const putExtra = {
        fname: '',
        params: {},
        mimeType: ['image/png', 'image/jpeg', 'image/gif']
      }
      const config = {
        region: qiniu.region.z0
      }
      const key = new Date().getTime()

      const observable = qiniu.upload(file, key, token, putExtra, config)
      const observer = {
        complete: res => {
          const imgUrl = baseUrl + '/' + res.key

          this.handlePostSuccess(imgUrl)
          onSuccess(res, file)
        },
        error: err => {
          notification.error({
            message: err
          })
          onError()
        },
        next: res => {
          onProgress({ percent: res.percent }, file)
        }
      }

      observable.subscribe(observer)

      return {
        abort() {
          console.log('upload progress is aborted.')
        }
      }
    } catch (err) {
      notification.error({ message: err })
    }
  }

  async componentDidMount() {
    const response = await API.getQiniuToken()
    const { baseUrl, token } = response.data
    this.setState({
      token,
      baseUrl
    })
  }
}

PicturesWall.defaultProps = {
  successCb: () => {}
}

export default PicturesWall
